package org.example;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;

import java.time.Duration;


/**
 * Hello world!
 */
public class Ehcache3 {
    public static void main(String[] args) throws InterruptedException {


// 1. 创建 CacheManager（无需设置全局上限）
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .build(true); // 初始化

// 2. 单独配置 Cache A：最多 1000 个条目
        CacheConfigurationBuilder<Object, Object> configA =
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                        Object.class, Object.class,
                        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(3, EntryUnit.ENTRIES) // ✅ 限制为 1000 个条目
//                        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(1000, EntryUnit.ENTRIES) // ✅ 限制为 1000 个条目
                );
// 3. 单独配置 Cache B：最多 500 个条目
        CacheConfigurationBuilder<Object, Object> configB =
                CacheConfigurationBuilder.newCacheConfigurationBuilder(
                        Object.class, Object.class,
                        ResourcePoolsBuilder.newResourcePoolsBuilder().heap(500, EntryUnit.ENTRIES) // ✅ 限制为 500 个条目
                ).withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMinutes(10)))
                        ;

// 4. 创建缓存（各自独立上限）
        Cache cache = cacheManager.createCache("users", configA);

        cacheManager.createCache("orders", configB);
        // 使用
        cache.put(1L, "Charlie");
        Thread.sleep(1000);
        System.out.println("Hello World 11!" + cache.get(1L));
        cache.put(2L, "Charlie11");
        Thread.sleep(1000);
        System.out.println("Hello World 11!" + cache.get(1L));
        Thread.sleep(1000);
        cache.put(3L, "Charlie1122");
        Thread.sleep(1000);
        System.out.println("Hello World 11!" + cache.get(1L));
        Thread.sleep(1000);
        cache.put(4L, "Charlie112233");
        System.out.println("Hello World 11!" + cache.get(1L));
        // 缓存统计信息，在ehcache3下，已不再支持获取size，
        System.out.println("Hello World 44!" + cache.get(4L));
        System.out.println("Hello World 22!" + cache.get(2L));
        System.out.println("Hello World 11!" + cache.get(1L));
    }
}
